package de.hijacksoft.isle;

import static de.hijacksoft.isle.classes.Variables.*;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.ContentValues;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.res.AssetFileDescriptor;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.ConnectivityManager;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.preference.PreferenceManager;
import android.provider.MediaStore;
import android.text.Editable;
import android.text.TextWatcher;
import android.text.method.DigitsKeyListener;
import android.util.Log;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnFocusChangeListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import com.example.android.apis.graphics.ColorPickerDialog;
import com.example.android.apis.graphics.ColorPickerDialog.OnColorChangedListener;
import de.hijacksoft.isle.adapters.BarcooDBAdapter;
import de.hijacksoft.isle.classes.Category;
import de.hijacksoft.isle.adapters.DBAdapter;
import de.hijacksoft.isle.classes.Item;
import de.hijacksoft.isle.adapters.ProgressListener;
import de.hijacksoft.isle.classes.Variables;
import java.util.ArrayList;

/**
 * This Activity is used to edit items and create new ones
 * @author HiJack Soft
 */
public class ItemActivity extends Activity {

    // Constants
    private static final String TAG = "ItemActivity";
    // Views
    private ImageView photo, colorpick, delete;
    private EditText name, price, amount;
    private Spinner unit, category;
    private Button scan, ok, cam;
    File[] imageFiles;  // for the pictures on the sdcard
    private DBAdapter adapter;
    private boolean editMode = false;
    private Item editedItem = new Item();
    protected Uri imageUri;
    private long itembarcode = 0;
    private int color = 0x000000;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_NOSENSOR);
        createUI();
        initDB();
        Intent data = getIntent();
        try {
            Item item = adapter.getItemById(data.getExtras().getInt(KEY_ID));
            itembarcode = item.barcode;
            name.setText(item.name);
            price.setText("" + item.price);
            price.setText(price.getText().toString() + ItemActivity.this.getString(R.string.currency));
            if (price.getText().toString().equals(ItemActivity.this.getString(R.string.currency))) {
                price.setText("");
            }
            amount.setText("" + item.amount);
            ok.setText(getString(R.string.apply));
            editMode = true;
            editedItem = item;
            char u = item.unit;
            unit.setSelection(u == 'k' ? 0 : u == 'g' ? 1 : u == 'l' ? 2 : u == 'm' ? 3 : 4);
            photo.setImageBitmap(readBitmap(item.image));
        } catch (Exception e) {
        }
        initSpinner();
        checkOkButton();
        checkDeleteButton();
    }

    /**
     * checks if the ok button should be disabled
     */
    private void checkOkButton() {
        if (name.getText().toString().equals("")) {
            ok.setEnabled(false);
        } else {
            ok.setEnabled(true);
        }
    }

    /**
     * checks if the ok button should be disabled
     */
    private void checkDeleteButton() {
        if (editedItem.category.id != Category.UNCATEGORIZED && editedItem.category.id != Category.NEW_CATEGORY) {
            delete.setEnabled(true);
        } else {
            delete.setEnabled(false);
        }
    }

    private void initDB() {
        adapter = new DBAdapter(this);
        adapter.open();
    }

    private void initSpinner() {
        // initialize category spinner
        final ArrayList<Category> categories = new ArrayList<Category>();
        ArrayAdapter<Category> stringAdapter = new ArrayAdapter<Category>(ItemActivity.this, R.layout.simple_spinner_item, categories);
        // add uncategorized and new category to the list
        categories.add(new Category(Category.NEW_CATEGORY, getString(R.string.new_), 0xffff00));
        categories.add(new Category(Category.UNCATEGORIZED, getString(R.string.uncategorized), 0xaaaaaa));

        // initialize names of categories
        ArrayList<Category> cats = adapter.getCategories();
        for (Category category : cats) {
            if (!category.isRecipe) {
                categories.add(category);
            }
        }

        category.setPrompt(getString(R.string.category));

        category.setAdapter(stringAdapter);

        category.setSelection(1);

        final int maxSize = categories.size();

        // check whether to create a new category
        category.setOnItemSelectedListener(new OnItemSelectedListener() {

            @Override
            public void onItemSelected(AdapterView<?> arg0, View arg1, int pos, long arg3) {

                Category selectedCategory = (Category) category.getItemAtPosition(pos);

                // new category was selected
                if (selectedCategory.id == Category.NEW_CATEGORY) {
                    AlertDialog.Builder alert = new AlertDialog.Builder(ItemActivity.this);

                    // set selection to original category in case the user cancels the dialog
                    category.setSelection(1);

                    alert.setTitle(getString(R.string.new_category));
                    alert.setMessage(getString(R.string.name) + ":");

                    // Set an EditText view to get user input
                    final EditText input = new EditText(ItemActivity.this);
                    alert.setView(input);
                    input.setText("");

                    // on apply:
                    alert.setPositiveButton(getString(R.string.apply),
                            new DialogInterface.OnClickListener() {

                                @Override
                                public void onClick(DialogInterface dialog, int whichButton) {
                                    // update new category
                                    String newCatName = input.getText().toString();

                                    // no name entered
                                    if (newCatName.replaceAll(" ", "").equals("")) {
                                        editedItem.category.id = Category.UNCATEGORIZED;
                                    }

                                    // check if category already exists
                                    boolean exists = false;
                                    for (Category cats : categories) {
                                        if (cats.name.equals(newCatName)) {
                                            exists = true;
                                        }
                                    }

                                    if (!exists) {
                                        Log.d(TAG, "new Category added");

                                        // add the new category to the category db
                                        Category c = new Category();
                                        c.name = newCatName;
                                        adapter.addCategory(c);

                                        c.id = adapter.getCategoryIdByName(c.name);

                                        // remove the last entry if it is a "new" category that doesnt exist yet
                                        //if (categories.size() > maxSize) {
                                        //    categories.remove(categories.size() - 1);
                                        //}

                                        // set the new category
                                        editedItem.category = c;

                                        categories.add(editedItem.category);

                                    }
                                    category.setSelection(categories.indexOf(editedItem.category));
                                }
                            });

                    alert.setNegativeButton(getString(R.string.cancel), null);
                    alert.show();

                } else {
                    editedItem.category = (Category) category.getItemAtPosition(pos);
                    colorpick.setBackgroundColor(editedItem.category.color);
                }

                checkDeleteButton();

            }

            @Override
            public void onNothingSelected(AdapterView<?> arg0) {
                // set the entry to the items category
                for (int i = 0; i < category.getCount(); i++) {
                    Category selectedCategory = (Category) category.getItemAtPosition(i);
                    if (selectedCategory.id == editedItem.id) {
                        category.setSelection(i);
                    }
                }
            }
        });

        // set the entry to the items category
        for (int i = 0; i < category.getCount(); i++) {
            Category selectedCategory = (Category) category.getItemAtPosition(i);
            if (selectedCategory.id == editedItem.category.id) {
                category.setSelection(i);
                break;
            }
        }

    }

    private void createUI() {

        setContentView(R.layout.additem);
        
        photo = (ImageView) findViewById(R.id.additem_imgview_photo);
        name = (EditText) findViewById(R.id.additem_edittext_name);
        amount = (EditText) findViewById(R.id.additem_edittext_amount);
        price = (EditText) findViewById(R.id.additem_edittext_price);
        unit = (Spinner) findViewById(R.id.additem_spinner_unit);
        scan = (Button) findViewById(R.id.additem_btn_scan);
        cam = (Button) findViewById(R.id.additem_btn_photo);
        ok = (Button) findViewById(R.id.additem_btn_ok);
        delete = (ImageView) findViewById(R.id.additem_btn_delete);
        category = (Spinner) findViewById(R.id.additem_spinner_category);
        colorpick = (ImageView) findViewById(R.id.additem_btn_colorpick);

        price.setKeyListener(DigitsKeyListener.getInstance(false, true));
        amount.setKeyListener(DigitsKeyListener.getInstance(false, true));

        if (!PreferenceManager.getDefaultSharedPreferences(this).getBoolean(Variables.PREFERENCE_SHOWCATEGORY, false)) {
            category.setVisibility(View.GONE);
            ((TextView) findViewById(R.id.additem_textview_category)).setVisibility(View.GONE);
            colorpick.setVisibility(View.GONE);
            delete.setVisibility(View.GONE);
        }

        delete.setOnClickListener(new OnClickListener() {

            public void onClick(View arg0) {

                AlertDialog.Builder dB = new AlertDialog.Builder(ItemActivity.this);

                dB.setTitle(getString(R.string.deleteitem).replace("$n", getString(R.string.category)));
                dB.setMessage(getString(R.string.deleteitem).replace("$n", editedItem.category.name));

                dB.setPositiveButton(R.string.yes, new DialogInterface.OnClickListener() {

                    public void onClick(DialogInterface dialog, int id) {
                        adapter.removeCategory(editedItem.category);
                        category.setSelection(1);
                        initSpinner();
                    }
                });

                dB.setNegativeButton(R.string.no, new DialogInterface.OnClickListener() {

                    public void onClick(DialogInterface dialog, int id) {
                        // do nothing
                    }
                });

                AlertDialog d = dB.create();
                d.show();

            }
        });

        colorpick.setOnClickListener(new OnClickListener() {

            public void onClick(View arg0) {
                ColorPickerDialog colorDialog = new ColorPickerDialog(ItemActivity.this,
                        new OnColorChangedListener() {

                            public void colorChanged(int color) {
                                colorpick.setBackgroundColor(color);
                                editedItem.category.color = color;
                            }
                        }, color);
                colorDialog.show();
            }
        });

        scan.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                // try starting a barcode scanner
                try {
                    Intent intent = new Intent("com.google.zxing.client.android.SCAN");
                    startActivityForResult(intent, BARCODE_ACTIVITY_REQUEST_CODE);
                } catch (Exception e) {
                    // alert the user, that no barcode scanner is installed
                    new AlertDialog.Builder(ItemActivity.this).setTitle(R.string.error).setMessage(R.string.noscanner).setPositiveButton(R.string.ok, null).create().show();
                }
            }
        });

        cam.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {

                //save the files in the camera folder to an array
                imageFiles = new File(CAMERA_FOLDER).listFiles();

                //create parameters for Intent with filename
                ContentValues values = new ContentValues();
                values.put(MediaStore.Images.Media.TITLE, "_islethumbnail.jpg");
                values.put(MediaStore.Images.Media.DESCRIPTION, "thumbnail to be used with ISLE");

                //imageUri is the current activity attribute, define and save it for later usage (also in onSaveInstanceState)
                imageUri = getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);

                //create new Intent
                Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
                startActivityForResult(intent, CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE);

            }
        });

        ok.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                if (!name.getText().toString().equals("")) {    // this check should be obsolete but is there for safety reasons

                    Intent intent = new Intent();
                    intent.putExtra(KEY_ID, adapter.getNextFreeItemId());

                    Item item = editedItem;

                    item.barcode = itembarcode;

                    long unitSpinner = unit.getSelectedItemPosition();
                    item.unit = unitSpinner == 0 ? 'k' : unitSpinner == 1 ? 'g' : unitSpinner == 2 ? 'l' : unitSpinner == 3 ? 'm' : 'p';

                    item.name = name.getText().toString();

                    item.image = imageUri;

                    try {
                        item.amount = Double.parseDouble(amount.getText().toString());
                    } catch (NumberFormatException e) {
                        Log.d(TAG, "Error parsing the Item amount: " + e.getMessage());
                    }

                    price.setText(price.getText().toString().replace(ItemActivity.this.getString(R.string.currency), ""));

                    try {
                        item.price = Double.parseDouble(price.getText().toString());
                    } catch (NumberFormatException e) {
                        Log.i(TAG, "Error parsing the Item price: " + e.getMessage());
                    }

                    // check if in edit mode and update/add item
                    if (editMode) {
                        // update item
                        adapter.updateItem(item);
                    } else {
                        adapter.addItem(item);
                    }

                    // update category
                    adapter.updateCategory(item.category);
                    Log.e(TAG, "color: " + item.category.color);

                    // finish the Activity with RESULT_OK
                    ItemActivity.this.setResult(RESULT_OK, intent);
                    ItemActivity.this.finish();

                }
            }
        });

        price.setFocusable(true);
        price.setOnFocusChangeListener(new OnFocusChangeListener() {

            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if (hasFocus) {
                    // remove the currency from the end of the EditText
                    price.setText(price.getText().toString().replace(ItemActivity.this.getString(R.string.currency), ""));
                } else {
                    // append the currency to the EditText
                    price.setText(price.getText().toString() + ItemActivity.this.getString(R.string.currency));
                    // remove the currency if the price equals ""
                    if (price.getText().toString().equals(ItemActivity.this.getString(R.string.currency))) {
                        price.setText("");
                    }
                }
            }
        });

        name.setFocusable(true);
        name.addTextChangedListener(new TextWatcher() {

            @Override
            public void afterTextChanged(Editable s) {
                checkOkButton();
            }

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
                checkOkButton();
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                checkOkButton();
            }
        });

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {

        switch (requestCode) {

            case BARCODE_ACTIVITY_REQUEST_CODE:
                if (resultCode == RESULT_OK) {

                    // get the barcode into a variable
                    long barcode = 0;
                    try {
                        barcode = Long.parseLong(data.getStringExtra("SCAN_RESULT"));
                    } catch (NumberFormatException e) {
                        Log.d(TAG, e.getMessage());
                        Toast.makeText(this, R.string.wrongbarcode, Toast.LENGTH_SHORT).show();
                        return;
                    }

                    // if the item has no barcode, set it.
                    if (itembarcode == 0) {
                        itembarcode = barcode;
                    }
                    if (itembarcode != 0 && itembarcode != barcode) {
                        // display a dialog that asks the user to change the barcode information
                        barcodeUpdateValueDialog(itembarcode, barcode);
                    }

                    // check if internet connection is available
                    ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
                    if (cm.getActiveNetworkInfo() != null && cm.getActiveNetworkInfo().isConnected()) {
                        DownloadInfoTask dt = new DownloadInfoTask();
                        dt.execute(barcode);
                    } else {
                        // display a dialog that tells the user that there is no internet connection available
                        checkInternetDialog();
                    }

                }
                break;

            case CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE:

                if (resultCode == RESULT_CANCELED) {

                    // Check for new images in the camera folder and delete them
                    File[] imageFilesAfterCam = new File(CAMERA_FOLDER).listFiles();
                    for (File check : imageFilesAfterCam) {
                        boolean delete = true;
                        for (File against : imageFiles) {
                            if (check.getName().equals(against.getName())) {
                                delete = false;
                            }
                        }
                        if (delete) {
                            check.delete();
                        }
                    }

                }

                if (resultCode == RESULT_OK) {
                    if (readBitmap(imageUri) != null && photo != null) {
                        photo.setImageBitmap(readBitmap(imageUri));
                    }
                    try {

                        // create a new directory for the thumbnails, the directory wont be deleted if it already exists
                        new File(Environment.getExternalStorageDirectory() + "/isle").mkdir();

                        if (!editMode) {

                            // Create a thumbnail of picture just taken at /sdcard/isle/
                            File imgfile = new File(Environment.getExternalStorageDirectory() + "/isle/" + adapter.getNextFreeItemId() + ".jpg");
                            FileOutputStream out = new FileOutputStream(imgfile);
                            Bitmap.createScaledBitmap(readBitmap(imageUri), THUMBNAIL_SIZE, THUMBNAIL_SIZE, false).compress(Bitmap.CompressFormat.JPEG, 90, out);

                            // Check for new images in the camera folder and delete them
                            File[] imageFilesAfterCam = new File(CAMERA_FOLDER).listFiles();
                            for (File check : imageFilesAfterCam) {
                                boolean delete = true;
                                for (File against : imageFiles) {
                                    if (check.getName().equals(against.getName())) {
                                        delete = false;
                                    }
                                }
                                if (delete) {
                                    check.delete();
                                }
                            }

                            // Set the imageUri to be saved into the database
                            imageUri = Uri.parse("file://" + Environment.getExternalStorageDirectory() + "/isle/" + adapter.getNextFreeItemId() + ".jpg");

                        } else {

                            // Create a thumbnail of picture just taken at /sdcard/isle/
                            File imgfile = new File(Environment.getExternalStorageDirectory() + "/isle/" + editedItem.id + ".jpg");
                            FileOutputStream out = new FileOutputStream(imgfile);
                            Bitmap.createScaledBitmap(readBitmap(imageUri), THUMBNAIL_SIZE, THUMBNAIL_SIZE, false).compress(Bitmap.CompressFormat.JPEG, 90, out);

                            // Delete the photo just taken from sdcard
                            String filepath = convertImageUriToFile(imageUri).toString().replace("/mnt", "").replaceAll(File.pathSeparator, "");
                            boolean fileExists = new File(filepath).delete();
                            Log.i(TAG, "DELETE " + filepath + ": " + (fileExists ? "sucess" : "failed"));

                            // Check for new images in the camera folder and delete them
                            File[] imageFilesAfterCam = new File(CAMERA_FOLDER).listFiles();
                            for (File check : imageFilesAfterCam) {
                                boolean delete = true;
                                for (File against : imageFiles) {
                                    if (check.getName().equals(against.getName())) {
                                        delete = false;
                                    }
                                }
                                if (delete) {
                                    check.delete();
                                }
                            }

                            // Set the imageUri to be saved into the database
                            imageUri = Uri.parse("file://" + Environment.getExternalStorageDirectory() + "/isle/" + editedItem.id + ".jpg");

                            // - - -

                            // Set the imageUri to be saved into the database
                            imageUri = Uri.parse("file://" + Environment.getExternalStorageDirectory() + "/isle/" + editedItem.id + ".jpg");

                        }
                    } catch (Exception e) {
                        // Do not print the Exception, because it would always result in an application crash
                        // The message is somehow empty/null
                        // Log.d(TAG, e.getMessage());
                    }
                }
                break;

        }
    }

    // - - - - - - - - - -
    // Dialogs start    
    private void barcodeUpdateValueDialog(final long local, final long online) {
        AlertDialog.Builder dB = new AlertDialog.Builder(this);

        dB.setTitle(R.string.update_barcode_title);
        dB.setMessage(R.string.update_barcode_msg);

        dB.setPositiveButton(R.string.yes, new DialogInterface.OnClickListener() {

            public void onClick(DialogInterface dialog, int id) {
                itembarcode = online;
            }
        });

        dB.setNegativeButton(R.string.no, new DialogInterface.OnClickListener() {

            public void onClick(DialogInterface dialog, int id) {
                itembarcode = local;
            }
        });

        AlertDialog d = dB.create();
        d.show();
    }

    private void nameUpdateValueDialog(final String local, final String online) {
        AlertDialog.Builder dB = new AlertDialog.Builder(this);

        dB.setTitle(R.string.update_name_title);
        dB.setMessage(R.string.update_name_msg);

        dB.setPositiveButton(R.string.yes, new DialogInterface.OnClickListener() {

            public void onClick(DialogInterface dialog, int id) {
                name.setText(online);
            }
        });

        dB.setNegativeButton(R.string.no, new DialogInterface.OnClickListener() {

            public void onClick(DialogInterface dialog, int id) {
                name.setText(local);
            }
        });

        AlertDialog d = dB.create();
        d.show();
    }

    private void priceUpdateValueDialog(final double local, final double online) {
        AlertDialog.Builder dB = new AlertDialog.Builder(this);

        dB.setTitle(R.string.update_price_title);
        dB.setMessage(R.string.update_price_msg);

        dB.setPositiveButton(R.string.yes, new DialogInterface.OnClickListener() {

            public void onClick(DialogInterface dialog, int id) {
                price.setText(online + "");
            }
        });

        dB.setNegativeButton(R.string.no, new DialogInterface.OnClickListener() {

            public void onClick(DialogInterface dialog, int id) {
                price.setText(local + "");
            }
        });

        AlertDialog d = dB.create();
        d.show();
    }

    private void notFoundDialog() {

        AlertDialog.Builder dB = new AlertDialog.Builder(this);
        dB.setTitle(R.string.error);
        dB.setMessage(R.string.itemnotfound);

        dB.setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {

            public void onClick(DialogInterface dialog, int id) {
            }
        });

        AlertDialog d = dB.create();
        d.show();

    }

    private void checkInternetDialog() {

        AlertDialog.Builder dB = new AlertDialog.Builder(this);
        dB.setTitle(R.string.error);
        dB.setMessage(R.string.checkinternet);

        dB.setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {

            public void onClick(DialogInterface dialog, int id) {
            }
        });

        AlertDialog d = dB.create();
        d.show();
    }
    // Dialogs end
    // - - - - - - - - - -

    /**
     * Reads a bitmap from an uri
     * @param selectedImage the uri where the image is
     * @return returns a bitmap of the image at the uri
     */
    private Bitmap readBitmap(Uri selectedImage) {
        Bitmap bm = null;
        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inSampleSize = 2; //reduce quality 
        AssetFileDescriptor fileDescriptor = null;
        try {
            fileDescriptor = this.getContentResolver().openAssetFileDescriptor(selectedImage, "r");
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } finally {
            try {
                bm = BitmapFactory.decodeFileDescriptor(fileDescriptor.getFileDescriptor(), null, options);
                fileDescriptor.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return bm;
    }

    /**
     * Converts an Uri to a File
     * @param imageUri the uri to be converted
     * @return returns a File object
     */
    private File convertImageUriToFile(Uri imageUri) {
        Activity activity = this;
        Cursor cursor = null;
        try {
            String[] proj = {MediaStore.Images.Media.DATA, MediaStore.Images.Media._ID, MediaStore.Images.ImageColumns.ORIENTATION};
            cursor = activity.managedQuery(imageUri,
                    proj, // Which columns to return
                    null, // WHERE clause; which rows to return (all rows)
                    null, // WHERE clause selection arguments (none)
                    null);      // Order-by clause (ascending by name)
            int file_ColumnIndex = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
            if (cursor.moveToFirst()) {
                return new File(cursor.getString(file_ColumnIndex));
            }
            return null;
        } finally {
            if (cursor != null) {
                cursor.close();
            }
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        startActivity(new Intent(this, Preferences.class));
        return false;//friert sonst den screen ein
    }

    /**
     * This method was used for demonstration and barcode scan testing and was replaced by the BarcooDBAdapter method getItem.
     * @deprecated
     * @param content The contents of the QRCode
     */
    public static Item getItemFromQRCode(String content) {

        Pattern p = Pattern.compile("(\\w|.)+\\n?");
        Matcher m = p.matcher(content);

        String match = "";

        Item item = new Item(null, 0, 0, 'g', null);

        int i = 0;

        while (m.find()) {
            match = m.group();
            Log.d(TAG, match);

            switch (i) {
                case 0:
                    item.name = match;
                    break;
                case 1:
                    item.amount = Double.parseDouble(match);
                    break;
                case 2:
                    item.price = Double.parseDouble(match);
                    break;
                case 3:
                    item.unit = match.charAt(0);
                    break;
                case 4:
                    item.image = Uri.parse(match);
                    break;
            }

            i++;
        }

        return item;

    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {

        switch (keyCode) {
            // start barcode scanner with search key
            case KeyEvent.KEYCODE_SEARCH:
                try {
                    Intent intent = new Intent("com.google.zxing.client.android.SCAN");
                    startActivityForResult(intent, BARCODE_ACTIVITY_REQUEST_CODE);
                } catch (Exception e) {
                    new AlertDialog.Builder(ItemActivity.this).setTitle(R.string.error).setMessage(R.string.noscanner).setPositiveButton(R.string.ok, null).create().show();
                }
                break;
        }

        return super.onKeyDown(keyCode, event);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        adapter.close();
    }

    /**
     * This class is a nearly complete copy of the DownloadTask in the ListActivity
     */
    private class DownloadInfoTask extends AsyncTask<Long, Integer, Integer> implements ProgressListener {

        ProgressDialog progressDialog;
        Item onlineItem;

        @Override
        protected void onPreExecute() {

            progressDialog = new ProgressDialog(ItemActivity.this);
            progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
            progressDialog.setTitle(R.string.retrieveinfo_title);
            progressDialog.setMessage(ItemActivity.this.getString(R.string.retrieveinfo_msg));
            progressDialog.setCancelable(false);
            progressDialog.show();

            BarcooDBAdapter.addProgressListener(this);
        }

        @Override
        protected Integer doInBackground(Long... barcode) {

            onlineItem = BarcooDBAdapter.getItem(barcode[0]);
            return null;

        }

        @Override
        protected void onPostExecute(Integer result) {

            progressDialog.dismiss();
            BarcooDBAdapter.removeProgressListener(this);

            if (onlineItem != null) {

                if (onlineItem.id != BarcooDBAdapter.NOTFOUNDID) {
                    String itemname = name.getText().toString();

                    if ((itemname == null || itemname.equals(""))) {
                        name.setText(onlineItem.name);
                    }
                    if ((itemname != null && !itemname.equals("")) && !itemname.equals(onlineItem.name)) {
                        nameUpdateValueDialog(itemname, onlineItem.name);
                    }

                    double itemprice = 0;
                    try {
                        itemprice = Double.parseDouble(price.getText().toString().replaceAll(ItemActivity.this.getString(R.string.currency), ""));
                    } catch (NumberFormatException e) {
                        Log.i(TAG, "couldnt parse the price: dont worry, this is normal if no price entered");
                    }

                    if (itemprice == 0) {
                        itemprice = onlineItem.price;
                    }
                    if (itemprice != 0 && itemprice != onlineItem.price && onlineItem.price != 0) {
                        priceUpdateValueDialog(itemprice, onlineItem.price);
                    }

                    if (itemprice != 0) {
                        price.setText("" + itemprice);
                    }

                    price.setText(price.getText().toString() + ItemActivity.this.getString(R.string.currency));
                    if (price.getText().toString().equals(ItemActivity.this.getString(R.string.currency))) {
                        price.setText("");
                    }
                } else {
                    notFoundDialog();
                }
            } else {
                checkInternetDialog();
            }

        }

        public void onProgressUpdate(int progress) {
            progressDialog.setProgress(progress);
        }
    }
}
